package com.zmn.oms.zmn.business.impl.work.autoflow.state;

import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.oms.business.interfaces.base.BaseCodeService;
import com.zmn.oms.business.interfaces.eventsnotice.EventsNoticeBService;
import com.zmn.oms.common.constant.OmsEventsConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.model.dto.order.ConfirmDTO;
import com.zmn.oms.model.entity.advancequote.AdvanceQuoteOpenQuery;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.zmn.business.interfaces.order.ZsOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.state.WorkAutoFlowBService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 类描述：确认
 * @author heciqi
 * @date 2019/10/28 20:06
 */
@Service("flowConfirmBService")
public class FlowConfirmBServiceImpl<T> implements WorkAutoFlowBService<T>{
	@Autowired
	OrderDetailService orderDetailService;
	@Autowired
	ZsOrderBService zsOrderBService;
	@Resource
	private OrderProductService orderProductService;
	@Autowired
	private EventsNoticeBService eventsNoticeBService;
	@Autowired
	private BaseCodeService baseCodeService;

	@Override
	public ResultDTO<T> condition(OrderWork orderWork) {
		if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_INPUT)) {
			return ResultDTO.fail("非已录入");
		}

		if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_COMPENSATE)) {
			return ResultDTO.fail("赔偿单不可操作");
		}

		Integer productId = orderWork.getProductId();
		if (Objects.equals(OrderConsts.CHANNEL_DISABLED_PRODUCT_ID, productId)
				|| Objects.equals(OrderConsts.CHANNEL_DISABLED_PRODUCT_ID_CLEAN, productId)) {
			return ResultDTO.fail("禁用产品：" + productId);
		}

		// 当订单“业务线&产品组&前后台产品分类（一级和二级）”为空时，不能确认，包括：自动确认、人工确认
		if (NumberUtil.isNullOrZero(orderWork.getBizLine())
				|| NumberUtil.isNullOrZero(orderWork.getServProductGroupId())
				|| NumberUtil.isNullOrZero(orderWork.getCategId())
				|| NumberUtil.isNullOrZero(orderWork.getShowCategId())) {
			return ResultDTO.fail("无业务线&产品组&前后台产品分类，不能自动确认");
		}

		OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(orderWork.getOrderId());

		// 非真实号码，不自动确认
		if (StringUtils.isBlank(orderDetail.getTelephone()) || MobileUtil.isExtensionPhone(orderDetail.getTelephone())) {
			return ResultDTO.fail("号码不存在或非真实号码，不自动确认");
		}

		if (Objects.equals(com.zmn.consts.GlobalConsts.BIZ_TYPE_F, orderWork.getBizType())) {
			// F单有城市，也可确认，包括：人工和系统确认，包括：API过来的F端订单；
			// TODO liuying  以及非厂商的一些特殊渠道，如：天猫
			if (NumberUtil.isNullOrZero(orderDetail.getCountyId())) {
				return ResultDTO.fail("没有区域信息");
			}
		} else {
			if (Objects.isNull(orderDetail.getLatitude()) || orderDetail.getLatitude() == 0d) {
				eventsNoticeBService.notice(orderWork, orderDetail, OmsEventsConsts.ORDER_CONFIRM_FAIL);
				return ResultDTO.fail(StatusConsts.ERROR_PARAMS, "经纬度不存在");
			}

			// 预约时间为空
			if (Objects.isNull(orderWork.getDutyTime())) {
				eventsNoticeBService.notice(orderWork, orderDetail, OmsEventsConsts.ORDER_CONFIRM_FAIL);
				return ResultDTO.fail(StatusConsts.ERROR_PARAMS, "平台无预约时间");
			}
		}

		// 是否返修新单
		boolean isReworkNew = Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)
				&& Objects.equals(orderWork.getChannelId(), OrderConsts.CHANNEL_ID_PLAT_REWORK_NEW_ORDER)
				&&  NumberUtil.isNotNullOrZero(orderWork.getOriginalId());

		if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW) && !isReworkNew) {
			if ((NumberUtil.isNullOrZero(orderWork.getOriginalAmount()) || NumberUtil.isNullOrZero(orderWork.getProductId()))) {
				// 提前报价试点
				AdvanceQuoteOpenQuery advanceQuoteOpenQuery = AdvanceQuoteOpenQuery.builder()
						.cityId(orderWork.getCityId())
						.servCategId(orderWork.getServCategId())
						.showProductType(NumberUtil.isNotNullOrZero(orderWork.getProductId()) ? BaseProductConsts.ERP_SHOW_TYPE : BaseProductConsts.EC_SHOW_TYPE)
						.productId(NumberUtil.isNotNullOrZero(orderWork.getProductId()) ? orderWork.getProductId() : orderWork.getShowProductId())
						.build();
				boolean openAdvanceQuote = baseCodeService.isOpenAdvanceQuote(advanceQuoteOpenQuery);
				if (openAdvanceQuote) {
					return ResultDTO.fail("提前报价试点，未产生价格，不自动确认");
				}
			}
		}

		return ResultDTO.success(orderWork);
	}

	@Override
	public void execute(T t) {
		OrderWork orderWork = (OrderWork) t;
		ConfirmDTO confirmDTO = new ConfirmDTO();
		confirmDTO.setOrderId(orderWork.getOrderId());
		confirmDTO.setWorkId(orderWork.getWorkId());
		confirmDTO.setStatus(OrderStatusConsts.WORK_STATUS_CONFIRM);
		confirmDTO.setConfirmerId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
		confirmDTO.setConfirmTime(DateUtil.getNow());
		confirmDTO.setOperator("系统");
		confirmDTO.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
		confirmDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
		zsOrderBService.confirmOrderSimple(confirmDTO);
	}
}
